<?php
namespace app\command;


use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\common\service\GuguService;


class MajorLine extends Command
{
    protected function configure()
    {
        $this->setName('major_line')->setDescription('Your command description');
    }

    protected function execute(Input $input, Output $output)
    {
        
        for ($task = 1; $task <= 97; $task++) {
            $process = new \Swoole\Process(function () use ($task) {
               $this->start_task($task);;
            }, false);
            $process->start();
        }
        
        // 等待所有子进程完成
        while ($status = \Swoole\Process::wait(true)) {
            // 子进程退出
            //echo "Recycled #{$status['pid']}, code={$status['code']}, signal={$status['signal']}" . PHP_EOL;
            echo "子进程 {$status['pid']}退出\n";
        }
        echo "父进程 ".getmypid()."退出\n";
		setLog('major_line','执行完毕：');exit();
		
		
    }
	
	protected function start_task($task){
		
		echo "子进程 ".getmypid()."处理任务{$task} \n";
		$list = Db::name('school')->field('college_name')->page($task,31)->select();
		foreach($list as $key=>$school){
			$page = 1;
			$result = GuguService::make('/metadata/ceemajorline',['appkey'=>'TZK6DJZ5LVS6V8LYDAS9WE3K4TM8ZQWZ','pageindex'=>$page,'pagesize'=>100,'schoolname'=>$school['college_name']]);
			if($result[0] != 200){
			   setLog('major_line','没有数据1：'.$school['college_name']);
			   continue;
			}
			$page_total = ceil($result[1][0]['DataTotalCount']/100);
			for($page=1;$page<=$page_total;$page++){
				$result = GuguService::make('/metadata/ceemajorline',['appkey'=>'TZK6DJZ5LVS6V8LYDAS9WE3K4TM8ZQWZ','pageindex'=>$page,'pagesize'=>100,'schoolname'=>$school['college_name']]);
				$dataM = [];
				$nowtime = time();
				if(!empty($result[1][1])){
					foreach($result[1][1] as $k=>$v){
						$dataM[] = ['province_name'=>$v['ProvinceName'],'school_uuid'=>$v['SchoolUUID'],'school_name'=>$v['SchoolName'],'major_name'=>$v['MajorName'],'major_code'=>$v['MajorCode'],'year'=>$v['Year'],'high_socre'=>$v['HighSocre'],'average_score'=>$v['AverageScore'],'lowest_score'=>$v['LowestScore'],'lowest_section'=>$v['LowestSection'],'batch_name'=>$v['BatchName'],'type_name'=>$v['TypeName'],'pro_score'=>$v['ProScore'],'subject_selection'=>$v['SubjectSelection'],
						'major_standard_code'=>$v['MajorStandardCode'],
						'create_time'=>$nowtime];
					}
				}
				if(!empty($dataM)){
					$flag = Db::name('major_line')->insertAll($dataM);
					if(!$flag){
						setLog('major_line','插入出错：'.$school['college_name'].$page.'页');
					}
				}else{
					setLog('major_line','没有数据2：'.$school['college_name']);
				}
			}
			setLog('major_line','拉取成功：'.$school['college_name']);
		}
		
		
		echo "子进程 ".getmypid()."完成任务{$task} \n";
	}

}
